#include <bits/stdc++.h>

using namespace std;

struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution
{
public:
    TreeNode *ret = nullptr;
    TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q)
    {
        if ((long long)(root->val - p->val) * (root->val - q->val) <= 0)
        {
            ret = root;
        }
        else if (root->val < p->val && root->val < q->val)
        {
            lowestCommonAncestor(root->right, p, q);
        }
        else
        {
            lowestCommonAncestor(root->left, p, q);
        }
        return ret;
    }
};